package com.unittec.zk.provider.auth.controller;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import com.unittec.zk.provider.auth.entity.SysRole;
import com.unittec.zk.provider.auth.service.SysUserRoleService;
import com.unittec.zk.sdk.root.common.CommonConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.auth0.jwt.interfaces.Claim;
import com.unittec.zk.provider.auth.dto.UserInfo;
import com.unittec.zk.provider.auth.service.SysUserService;
import com.unittec.zk.provider.common.JwtTokenUtil;
import com.unittec.zk.provider.log.Log;
import com.unittec.zk.provider.utils.ValidationUtils;
import com.unittec.zk.sdk.auth.request.Req101801;
import com.unittec.zk.sdk.auth.response.Res101801;
import com.unittec.zk.sdk.root.common.FieldConstants;
import com.unittec.zk.sdk.root.domain.GatewayRequest;
import com.unittec.zk.sdk.root.domain.Result;
import com.unittec.zk.sdk.root.enums.BizCode;
import com.unittec.zk.sdk.root.enums.BizCodeEnum;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * @author: trace
 * @date: 2019-06-12.
 * @Description:
 * @Email: tracenet@126.com
 */
@RestController
@Api(tags = "token管理")
public class AuthController {

    @Autowired
    Log log;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysUserRoleService sysUserRoleService;

    @RequestMapping(value = "/1")
    @ResponseBody
    public void showInfo() throws IOException {
        Properties properties = new Properties();
        properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("META-INF/maven/com.unittec.zk/zk-auth-101/pom.properties"));
        properties.entrySet().forEach(prop -> System.out.println(prop.getKey() + "=" + prop.getValue()));
    }

    @RequestMapping(value = "/101801", method = RequestMethod.POST)
    @ApiOperation(value = "校验token", notes = "校验token")
    @ResponseBody
    public Result<Res101801> verifyToken(@RequestBody GatewayRequest<Req101801> req) {
        log.debug(req, "verifyToken {}  ", "begin");
        BizCodeEnum bizCodeEnum = BizCode.ERROR;
        Res101801 res101801 = null;
        try {
            ValidationUtils.validateEntityStr(req.getContent());
            String token = req.getContent().getToken();
            if (JwtTokenUtil.checkToken(token)) {
                Map<String, Claim> claimMap = JwtTokenUtil.verifyToken(token);
                String userId = claimMap.get(FieldConstants.LOGIN_USER).asString();
                if (userId != null) {
                    UserInfo userInfo = sysUserService.getUserInfoById(userId);
                    if (userInfo != null) {
                        token = JwtTokenUtil.createToken(userInfo.getId(), userInfo.getUsername(), userInfo.getTenantId(), req.getAppKey(), req.getAppId());
                        res101801 = new Res101801();
                        res101801.setToken(token);
                        res101801.setUserId(userInfo.getId());
                        res101801.setUsername(userInfo.getUsername());
                        res101801.setRealname(userInfo.getRealname());
                        res101801.setAvatar(userInfo.getAvatar());
                        res101801.setUserType(userInfo.getType());
                        res101801.setPlatformCode(userInfo.getPlatformCode());
                        res101801.setTenantId(userInfo.getTenantId());
                        Boolean isAdmin = Boolean.FALSE;
                        List<SysRole> roleList = sysUserRoleService.getSysRoleByUserId(userInfo.getId());
                        if (roleList != null && roleList.size() > 0) {
                            StringBuilder userRole = new StringBuilder();
                            StringBuilder userRoleId = new StringBuilder();
                            for (int i = 0; i < roleList.size(); i++) {
                                SysRole sysRole = roleList.get(i);
                                if (sysRole.getRoleCode().equalsIgnoreCase(CommonConstant.ADMIN_ROLE_CODE)) {
                                    isAdmin = Boolean.TRUE;
                                }
                                if (i != 0) {
                                    userRole.append("," + sysRole.getRoleCode());
                                    userRoleId.append("," + sysRole.getId());
                                } else {
                                    userRole.append(sysRole.getRoleCode());
                                    userRoleId.append(sysRole.getId());
                                }
                            }
                            res101801.setUserRole(userRole.toString());
                            res101801.setUserRoleId(userRoleId.toString());
                        }
                        res101801.setIsAdmin(isAdmin);
                        bizCodeEnum = BizCode.SUCCESS;
                    }
                } else {
                    bizCodeEnum = BizCode.TOKEN_ERROR;
                }
            } else {
                bizCodeEnum = BizCode.TOKEN_EXPIRE;
            }
        } catch (Exception e) {
            log.error(req, e.toString(), e);
            return Result.error(req, e.getMessage());
        }
        log.debug(req, "verifyToken {}  ", "end");
        if (bizCodeEnum == BizCode.SUCCESS) {
            return Result.success(req, res101801);
        } else {
            return Result.error(req, bizCodeEnum);
        }
    }

}
